package com.cyj.dream.core.handler;

import com.cyj.dream.core.constant.enums.ResultCode;
import com.cyj.dream.core.exception.BizException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.DispatcherType;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.concurrent.TimeUnit;

/**
 * @Description: 防止重复请求--根据JWT生成的token颗粒度比较大
 * @BelongsProject: DreamChardonnay
 * @BelongsPackage: com.cyj.dream.core.handler
 * @Author: ChenYongJia
 * @CreateTime: 2021-09-26 11:04
 * @Email: chen87647213@163.com
 * @Version: 1.0
 */
@Component
public class RepeatSubmitInterceptor extends HandlerInterceptorAdapter {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    /**
     * 防重时间间隔（秒）
     */
    private final int duration = 1;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if (request.getDispatcherType() == DispatcherType.ERROR) {
            return true;
        }

        String token = request.getHeader("token");
        String lockKey = "RepeatSubmit:" + token + ":" + request.getServletPath();
        Boolean result = stringRedisTemplate.opsForValue().setIfAbsent(lockKey, "", duration, TimeUnit.SECONDS);
        if (!result) {
            // 请勿重复提交请求
            throw new BizException(ResultCode.DO_SUBMIT_REQUEST);
        }

        return true;
    }
}
